using Common.Commands;
using Common.Commands.TemplateCommands;
using Core.Domain.Model;
using Core.Infrastructure.CustomExceptions;
using Dto.ApiResponses.TemplateResponses;
using Sanelib.Common.Helpers;
using Sanelib.DataOperation;
using Sanelib.Dto;

namespace Core.Processors.TempleteProcessors
{
    public class AddTempleteProcessor : ICommandProcessor<AddTemplete>
    {
        private readonly IRepository<Templete> _templeteRepository;

        public AddTempleteProcessor(IRepository<Templete> templeteRepository)
        {
            _templeteRepository = templeteRepository;
        }

        public dynamic Process(AddTemplete command)
        {
            EnsureUniqueness(command);

            var templete = new Templete
                {
                    Id = command.Id,
                    Name = command.Name,
                    Value = command.Value,
                };

            _templeteRepository.Add(templete);

            var response = new TemplateResponse
            {
                Id = command.Id,
                Name = command.Name,
                Value = command.Value
            };

            return response;
        }

        private void EnsureUniqueness(AddTemplete command)
        {
            var templeteWithSameName = _templeteRepository.GetByKey(Property.Of<Templete>(entity => entity.Name), command.Name);

            if (templeteWithSameName != null)
            {
                throw new DomainProcessException("Template with same name exist.");
            }
        }
    }
}
